package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;

import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.RecreateTaskCtx;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseStringCallback;

public class RecreateTaskCallback extends BaseStringCallback {
	private static final Logger LOGGER = Logger.getLogger(RecreateTaskCallback.class);
	private Master master;
	
	public RecreateTaskCallback(Master master) {
		this.master = master;
	}
	
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx, String name) {
		RecreateTaskCtx context = (RecreateTaskCtx) ctx;
		master.recreateTask(context);
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, String name) {
		RecreateTaskCtx context = (RecreateTaskCtx) ctx;
		//任务重新创建成功后，删除原来的已经分配的任务
		master.deleteAssignment(context.getPath());
	}
	
	@Override
	protected void nodeExistsCaseAction(int rc, String path, Object ctx, String name) {
		LOGGER.info("Node exists already, but if it hasn't been deleted, " +
        		"then it will eventually, so we keep trying: " + path);
		RecreateTaskCtx context = (RecreateTaskCtx) ctx;
        master.recreateTask(context);
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			String name) {
		LOGGER.error("Something wwnt wrong when recreating task", 
                KeeperException.create(Code.get(rc)));
	}
}
